import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/view/ListSeparator.dart';
import 'package:im_app/im/page/view/LoadingView.dart';
import 'package:im_app/im/util/UiUtil.dart';

import '../../pojo/ImPojo.dart';
import '../../util/FileUtil.dart';
import '../../util/HexColor.dart';
import '../../util/ImConstant.dart';
import '../bloc/FileBrowseCubit.dart';
import '../view/component/UiUtil.dart';
import '../view/component/cell/FileItemView.dart';

class FileBrowsePage extends StatefulWidget {
  const FileBrowsePage({super.key});

  @override
  State<StatefulWidget> createState() => _FileBrowseState();
}

class _FileBrowseState extends State<FileBrowsePage> with SingleTickerProviderStateMixin {
  late TabController _tabController;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);

    var fileBrowseCubit = context.read<FileBrowseCubit>();
    fileBrowseCubit.add(FileBrowseLoadFileEvent(0));
  }

  @override
  Widget build(BuildContext context) {
    var fileBrowseCubit = context.watch<FileBrowseCubit>();
    return Scaffold(
      appBar: _buildAppBar(context),
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          TabBar(
              controller: _tabController,
              onTap: (value){ fileBrowseCubit.add(FileBrowseLoadFileEvent(value)); },
              // 下划线的大小
              tabs: const <Widget>[
                Tab(text: '聊天'),
                Tab(text: '收藏'),
                Tab(text: '手机'),
              ]),
          Expanded(
              child: TabBarView(controller: _tabController,
                  children: <Widget>[
                    LoadingView(
                        state: fileBrowseCubit.state.fileLoadingState,
                        child: _FileView(
                          files: fileBrowseCubit.state.searchFiles,
                          selectedFiles: fileBrowseCubit.state.selectedFiles,
                          fileViewType: FileViewType.file,
                        )
                    ),
                    LoadingView(
                        state: fileBrowseCubit.state.collectFileLoadingState,
                        child: _FileView(
                          files: fileBrowseCubit.state.searchCollectFiles,
                          selectedFiles: fileBrowseCubit.state.selectedCollectFiles,
                          fileViewType: FileViewType.collectFile,
                        )
                    ),
                    LoadingView(
                        state: fileBrowseCubit.state.systemFileLoadingState,
                        child: GestureDetector(
                          onTap: () async {
                            FilePickerResult? result = await FilePicker.platform.pickFiles(allowMultiple: true);

                            if (result != null) {
                              List<File> files = result.paths.map((path) => File(path!)).toList();
                            }
                          },
                          child: const Center(
                            child:  Text('打开手机选择器'),
                          ),
                        )
                    ),
              ])
          ),
        ],
      ),
    );
  }

  AppBar _buildAppBar(BuildContext context) {
    return AppBar(
      backgroundColor: ImConstant.IM_MAIN_BACKGROUND_COLOR,
      leading: GestureDetector(
        child: const Padding(
          padding: EdgeInsets.only(left: 15, top: 15),
          child: Text(
            '取消',
            style: TextStyle(color: Colors.blue),
          ),
        ),
        onTap: () => Navigator.of(context).pop(),
      ),
      centerTitle: true,
      title: const Text(
        '选择文件',
        style: TextStyle(color: Colors.black),
      ),
    );
  }
}

class _FileView extends StatefulWidget {
  final List<ImFile> files;
  final List<ImFile> selectedFiles;
  final FileViewType fileViewType;

  const _FileView({required this.files, required this.selectedFiles, required this.fileViewType, super.key});

  @override
  State<StatefulWidget> createState() => _FileViewState();
}

class _FileViewState extends State<_FileView> with TickerProviderStateMixin {
  late AnimationController controller;
  late Animation<double> positionAnimation;
  bool isShowSelectedPane = false;

  @override
  void initState() {
    super.initState();
    controller = AnimationController(
      duration: const Duration(microseconds: 200),
      vsync: this,
    );
    positionAnimation = Tween<double>(begin: -550, end: 0).animate(controller)
      ..addListener(() {
        setState(() {});
      });
  }

  @override
  Widget build(BuildContext context) {
    var fileBrowseCubit = context.read<FileBrowseCubit>();
    return Stack(
      alignment: AlignmentDirectional.bottomCenter,
      children: [
        ListView.separated(
            itemBuilder: (BuildContext context, int index) {
              return GestureDetector(
                  onTap: (){
                    if (widget.fileViewType == FileViewType.file) {
                      if (fileBrowseCubit.state.selectedFiles.contains(widget.files[index])) {
                        fileBrowseCubit.add(FileBrowseRemoveFileEvent(widget.files[index]));
                      } else {
                        fileBrowseCubit.add(FileBrowseAddFileEvent(widget.files[index]));
                      }
                    } else {
                      if (fileBrowseCubit.state.selectedCollectFiles.contains(widget.files[index])) {
                        fileBrowseCubit.add(FileBrowseRemoveCollectFileEvent(widget.files[index]));
                      } else {
                        fileBrowseCubit.add(FileBrowseAddCollectFileEvent(widget.files[index]));
                      }
                    }
                  },
                child: FileItemView(file: widget.files[index], fileViewType: widget.fileViewType,),
              );
            },
            separatorBuilder: (BuildContext context, int index) {
              return ListSeparator(
                indent: 10,
              );
            },
            itemCount: widget.files.length),
        buildSubmitPane(),
      ],
    );
  }

  Widget buildSubmitPane() {
    return AnimatedPositioned(
        duration: const Duration(milliseconds: 200),
        bottom: positionAnimation.value,
        left: 0,
        right: 0,
        child: Container(
          height: 600,
          decoration: BoxDecoration(
            borderRadius: const BorderRadius.only(topRight: Radius.circular(10), topLeft: Radius.circular(10)),
            color: HexColor.fromHex("#33918C8C"),
            // color: Colors.green,
          ),
          child: Column(
            children: [
              buildSubmitControlPane(),
              buildSelectedFileListPane(),
              if (isShowSelectedPane) _buildSubmitButtonPane()
            ],
          ),
        )
    );
  }

  Widget buildSubmitControlPane() {
    return Padding(
      padding: const EdgeInsets.only(left: 10, top: 10, right: 10, bottom: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          GestureDetector(
            onTap: () {
              if (!controller.isCompleted) {
                controller.forward();
                setState(() {
                  isShowSelectedPane = true;
                });
              } else {
                controller.reverse();
                setState(() {
                  isShowSelectedPane = false;
                });
              }
            },
            child: buildUpOrDownIcon(),
          ),

          Expanded(child: Text('已选中${widget.selectedFiles.length}个文件', textAlign: TextAlign.center,)),
          // Expanded(child: Text('已选中${widget.selectedFiles.length}个文件')),
          if (!isShowSelectedPane) _buildSubmitButton(),
        ],
      ),
    );
  }

  Widget buildUpOrDownIcon() {
    if (isShowSelectedPane) {
      return buildSvgView('assets/svg/down1.svg', 30, 30, Colors.black);
    } else {
      return buildSvgView('assets/svg/up1.svg', 30, 30, Colors.black);
    }
  }

  Widget buildSelectedFileListPane() {
    return SizedBox(
      height: 500,
      child: ListView.builder(
        itemBuilder: (BuildContext context, int index) {
          return buildSelectedFileItemView(widget.selectedFiles.elementAt(index));
        },
        itemCount: widget.selectedFiles.length,
      ),
    );
  }

  Widget _buildSubmitButtonPane() {
    return Padding(
      padding: const EdgeInsets.only(top: 10, right: 10),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [_buildSubmitButton()],
      ),);
  }

  Widget _buildSubmitButton() {
    return FilledButton(
      onPressed: widget.selectedFiles.isNotEmpty ? sendFiles : null,
      style: ButtonStyle(
        backgroundColor: WidgetStateProperty.all(Colors.green),
        shape: WidgetStateProperty.all(RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(5.0),
        )),
        padding: WidgetStateProperty.all(const EdgeInsets.only(left: 5, right: 5)),
      ),
      child: const Text('发送'),
    );
  }

  Widget buildSelectedFileItemView(ImFile imFile) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: Row(
        children: [
          Image(
            image: AssetImage(FileUtil.getFileImagePath(imFile.path)),
            width: 35,
            fit: BoxFit.contain,
          ),
          const SizedBox(width: 10,),
          Expanded(child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ConstrainedBox(
                constraints: const BoxConstraints(maxWidth: 275),
                child: Text(imFile.fileName),
              ),
              const SizedBox(height: 5,),
              Text(FileUtil.formatFileSize(imFile.fileSize), style: const TextStyle(color: Colors.grey,
                  fontSize: ImConstant.IM_SMALL_SIZE),
              ),
            ],
          )),
          TextButton(onPressed: () {
            var fileBrowseCubit = context.read<FileBrowseCubit>();
            if (widget.fileViewType == FileViewType.file) {
              fileBrowseCubit.add(FileBrowseRemoveFileEvent(imFile));
            } else {
              fileBrowseCubit.add(FileBrowseRemoveCollectFileEvent(imFile));
            }
          }, child: const Text('移除'),)
        ],
      ),
    );
  }

  // 发送文件
  sendFiles() {
    var fileBrowseCubit = context.read<FileBrowseCubit>();
    if (widget.fileViewType == FileViewType.file) {
      if (fileBrowseCubit.state.selectedFiles.isEmpty) {
        UiUtil.showSnackBar(context, '请选择文件');
        return;
      }
    } else {
      if (fileBrowseCubit.state.selectedCollectFiles.isEmpty) {
        UiUtil.showSnackBar(context, '请选择文件');
        return;
      }
    }
    fileBrowseCubit.add(FileBrowseLoadSendEvent(context, widget.fileViewType));
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}

enum FileViewType {
  file,
  collectFile,
}
